package com.itheima.service.impl;


import com.itheima.annotation.OperateLogAnnotation;
import com.itheima.exception.TliasException;
import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Emp;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

// 业务逻辑
@Service
@Scope("singleton")
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper dept;


    @Autowired
    private EmpService empService;

    @Override
    public List<Dept> getDeptList() {
        System.out.println(" 我是获取部门列表的ServiceImpl中的方法" );

        // int i = 1/0;
        // System.out.println("i = " + i);
        List<Dept> list = dept.selectList(null);
        return list;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperateLogAnnotation
    public void delDeptById(Integer id) throws Exception {
        // 删除之前先查询一下
      List<Emp> list = empService.selectEmpByDeptId(id);
        System.out.println("list = " + list);
      if(!CollectionUtils.isEmpty(list)){
          throw new TliasException("当前部门中还要人员存在,请先删除对应的员工");
      }
        dept.deleteById(id);
    }

    @Override
    @OperateLogAnnotation
    public void insertDept(Dept deptS) {

        deptS.setCreateTime(LocalDateTime.now());
        deptS.setUpdateTime(LocalDateTime.now());

        dept.insert(deptS);
    }

    @Override
    public Dept getEmpById(Integer id) {
        Dept dep= (Dept) dept.selectById(id);
        return dep;
    }

    @Override
    @OperateLogAnnotation
    public void updateDept(Dept d) {
        d.setUpdateTime(LocalDateTime.now());
        dept.updateById(d);


    }
}
